<?php
    if(isset($_POST['redeem'])){
        $db = new Database();
        $auth = Auth::getAuth('current_user');
        $userID = $auth['id'];
        $timezone = "Asia/Manila";
        if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
        $dealer_id = $_POST['dealer_id']; //this will be the key to find dealercode
        $products = implode($_POST['prodToBeInserted']);
        $product_type = stripcslashes($_POST['product_type']);
        $total_amount = $_POST['total_amount'];
        $quantities = implode($_POST['quantity']);
        $dealerCode = "";
        $transactionID = $_POST['trans_id'];
        //$select_dealerCode = $db->query("select dealerCode from tbdealer where dealerCode = '$dealer_id'","array");
        //foreach($select_dealerCode as $row){
            //$dealerCode = $row['dealerCode'];
        //}
        $getPoints = $db->query("SELECT * FROM tbdealer WHERE dealerCode='$dealer_id' and expiryDate > CURDATE()","array");
        foreach($getPoints as $data)
        {
            $dealerPoints = $data['pointsEarned'];
            foreach (extractForms($dealerPoints) as $key => $value) {
                if(isset($total[$key]))
                    $total[$key] += $value; 
                else
                    $total[$key] = $value;
            }
        }
        foreach ($total as $k => $v)  {
	    
	    $split = explode(" ", $k);
	    $header = $split[0]; // Header
	    
	    if(strpos($k, 'PLINE') !== false){
		$k = $split[1]; // Sub Header
	    }else{
		$k = $k; // Sub Header
	    }
	    
            if($product_type==$k){
            $points = redeemPoints($k,$v,$dealer_id);
            $remainingPoints = $points - $total_amount;
            }
        }
        if($total_amount>$points){
            echo "!";
        }else{
            $insert = array(
                    "trans_id"=>$transactionID,
                    "dealerCode"=>$dealer_id,
                    "product_id"=>$products,
                    "quantity"=>$quantities,
                    "product_type"=>$product_type,
                    "total"=>$total_amount,
                    "remaining_points"=>$remainingPoints,
                    "date"=>date("Y-m-d")
            );
            $db->insert('tbredeem',$insert);
            $audit = array(
			"user_id"=>$userID,
			"action_id"=>8,
			"affected_table"=>"tbredeem",
			"affected_record"=>$dealer_id,
			"datetime"=>date("Y-m-d  H:i:s"),
			"is_active"=>1
			);
            $db->insert("tbaudit_trail",$audit);
            $getLastID = $db->query("SELECT * FROM tbredeem","array");
            foreach($getLastID as $ID)
            {
                $id = $ID['id'];
            }
            echo $id;
        }
    }